@push('create_edit_css')
    <link rel="stylesheet" href="{{ cdn(elixir('assets/css/fileinput.css')) }}">
    <link rel="stylesheet" href="{{ cdn(elixir('assets/css/editor.css')) }}">
    <link rel="stylesheet" href="{{ cdn(elixir('assets/css/select2.css')) }}">
@endpush


@push('create_edit_js')
<script src="{{cdn('/assets/js/select2.min.js')}}"></script>
{{--<script src="{{cdn('/assets/js/zh-CN.js')}}"></script>--}}

{{--<script src="{{ cdn(elixir('assets/js/select2.js')) }}"></script>--}}
<script src="{{ cdn(elixir('assets/js/editor.js')) }}"></script>
<script src="{{ cdn(elixir('assets/js/fileinput.js')) }}"></script>
@endpush


@extends('layouts.default')

@section('title')
{{ isset($topic) ? '编辑话题' : lang('Create New Topic') }}_@parent
@stop

@section('content')

<div class="topic_create topic-create">

  <div class="col-md-8 col-md-offset-2 main-col">

    <div class="reply-box form box-block">

        <div class="header">
            {{!empty($category) && ($category->parent_id == config('phphub.homework_help_id') || $category->id == config('phphub.homework_help_id')) ? '提个问题' : '新建话题'}}
        </div>

      @include('layouts.partials.errors')

      @if (isset($topic))
        <form method="POST" action="{{ route('topics.update', $topic->id) }}" accept-charset="UTF-8" id="topic-edit-form" class="topic-form">
        <input name="_method" type="hidden" value="PATCH">
      @else
        <form method="POST" action="{{ route('topics.store') }}" accept-charset="UTF-8" id="topic-create-form" class="topic-form">
      @endif
        {!! csrf_field() !!}
        <div class="oneline-field form-group {{ (!empty($category) && $category->parent_id == 0) ?: 'col-md-4' }} {{!empty($category) && ($category->parent_id == config('phphub.homework_help_id') || $category->id == config('phphub.homework_help_id')) ? 'hidden' : ''}}" style="padding-left: 0;">
            <select class="selectpicker form-control" name="parent_category_id" id="parent-category-select" required="required" >
                @if(!empty($category) && ($category->parent_id == config('phphub.homework_help_id') || $category->id == config('phphub.homework_help_id')))
                    <option value="{{ $category->id }}" {{ !empty($category) ?: 'selected' }}>{{ $category->name }}</option>
                @else
                    <option value="" disabled {{ !empty($category) ?: 'selected' }}>{{ lang('Pick a category') }}</option>

                    @foreach ($categories as $value)
                        {{-- 如果用户可以发布公告，并且是 id == 3 的话 --}}
                        @if($value->id != 3 || Auth::user()->can('compose_announcement'))
                            @if(
                              ($value->id != config('phphub.admin_board_cid') || Auth::user()->can('access_board'))
                              && $value->parent_id === 0
                            )
                                <option value="{{ $value->id }}"
                                        {{ (!empty($category) && ($value->id == $category->parent_id || $value->id == $category->id)) ? 'selected' : '' }}
                                >{{ $value->name }}</option>
                            @endif
                        @endif
                    @endforeach

                @endif
            </select>
        </div>

        <div class="oneline-field form-group {{ (!empty($category) && $category->parent_id == 0) ? 'hidden' : '' }} col-md-8" style="padding-right: 0;">
            <select class="selectpicker form-control" name="category_id" id="category-select" required="required">

                <option value="" disabled {{ !empty($category) ?: 'selected' }}>{{ lang('Pick a son category') }}</option>

                @foreach ($categories as $value)
                    @if($value->id != 3 || Auth::user()->can('compose_announcement'))
                        @if (
                            ($value->id != config('phphub.admin_board_cid') || Auth::user()->can('access_board'))
                            && !empty($category)
                            && $value->parent_id == $category->parent_id
                        )
                            <option value="{{ $value->id }}" {{ (!empty($category) && $value->id == $category->id) ? 'selected' : '' }} >{{ $value->name }}</option>
                        @endif
                    @endif
                @endforeach

            </select>
        </div>
        <div class="clearfix"></div>

        {{--@foreach ($categories as $cat)--}}
            {{--<div class="category-hint alert alert-warning category-{{ $cat->id }} {{ !empty($category) && $cat->id == $category->parent_id ? 'animated rubberBand ' : ''}}" style="{{ (!empty($category) && $cat->id == $category->parent_id) ? '' : 'display:none' }}">--}}
                {{--{!! $cat->description !!}--}}
            {{--</div>--}}
        {{--@endforeach--}}

            <div class="form-group">
                <input class="form-control" id="topic-title" placeholder="{{lang('Please write down a topic') }}" name="title" type="text" value="{{ !isset($topic) ? '' : $topic->title }}" required="required">
            </div>

        <div class="form-group">
            <select class="form-control" style="width: 100%" id="tags" name="tags[]" type="text" multiple="multiple">
                @foreach($tags as $tag)
                    <option value="{{ $tag->name }}" {{ isset($topicTags) && in_array($tag->name, $topicTags) ? 'selected' : ''}}>{{ $tag->name }}</option>
                @endforeach
            </select>
        </div>

        @include('topics.partials.composing_help_block')


        <div class="form-group">
            <textarea class="form-control" rows="20" style="overflow:hidden" id="reply_content" placeholder="{{ lang('Please using markdown.') }}" name="body" cols="50">{{ !isset($topic) ? '' : $topic->body_original }}</textarea>
        </div>

        <div class="form-group status-post-submit">
            <button class="btn btn-primary submit-btn" id="topic-submit" type="submit">{{ lang('Publish') }}</button>
        </div>

      </form>
    </div>
  </div>

</div>

<script>
    Config.topic_id = '{{ isset($topic) ? $topic->id : 0 }}';
</script>

@stop


@section('scripts')

{{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/editor.css')) }}">--}}
{{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/select2.css')) }}">--}}
{{--<link rel="stylesheet" href="{{ cdn(elixir('assets/css/fileinput.css')) }}">--}}
{{--<script src="{{ cdn(elixir('assets/js/editor.js')) }}"></script>--}}
{{--<script src="{{ cdn(elixir('assets/js/select2.js')) }}"></script>--}}
{{--<script src="{{ cdn(elixir('assets/js/fileinput.js')) }}"></script>--}}
<style>
    .select2-search__field {
        width: 256px !important;
    }
    .select2-container--default.select2-container--focus {
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 181, 173, 0.6);
    }
    .select2-container--default.select2-container--focus .select2-selection--multiple {
        border: solid #00b5ad 1px;
    }
    .select2-container--default .select2-results__option--highlighted[aria-selected] {
        background-color: #00b5ad;
    }
    @media (max-width: 992px) {
        .oneline-field {
            padding: 0;
        }
    }
</style>
<script>
    var categories = {!! \App\Models\Category::tree(true) !!};
    var tags = $('#tags');
    var maxTagsSelected = 4;
    var current_cid = $('#parent-category-select').val();
    $(document).ready(function()
    {
        tags.select2({
            tags: true,
            tokenSeparators: [',', '，'],
            closeOnSelect: true,
            placeholder: "{{ lang('Input Tags') }}",
            maximumSelectionLength: maxTagsSelected,
            language: 'zh-CN',
            createTag: function(params) {
                return null;
            }
        });

        $('#topic-submit').on('click', function () {
            $('#parent_category_id').removeAttr('disabled');
            localStorage.smde_topic_content = ""
        });

        $(document).on('keyup', '.select2-selection--multiple .select2-search__field', function(event){
            if(event.keyCode == 13 || event.keyCode == 188){
                var $this = $(this);
                var optionText = $this.val().trim().replace(/[,;，；]*$/, '');
                if(optionText != "" && $this.find("option[value='" + optionText + "']").length === 0 && tags.find("option[value='" + optionText + "']").length === 0){
                    var $select = $this.parents('.select2-container').prev("select");
                    if (tags.find(":selected").length > maxTagsSelected - 1) {
                        return;
                    }
                    var newOption = new Option(optionText, optionText, true, true);
                    $select.append(newOption).trigger('change');
                    $this.val('');
                }
            }
        });

        @if ( ! isset($topic))
            localforage.getItem('topic-title', function(err, value) {
                if ($('#topic-title').val() == '' && !err) {
                    $('#topic-title').val(value);
                }
            });
            $('#topic-title').keyup(function(){
                localforage.setItem('topic-title', $(this).val());
            });
        @endif

        $('#parent-category-select').on('change', function(e) {
            current_cid = $(this).val();
            $('.category-hint').hide();
            $('.category-'+current_cid).fadeIn();

            $('#resource').addClass('hidden')
            $('#algorithm_source_hint').addClass('hidden')

            var subCategorySelect = $("#category-select");
            var parentCategorySelect = $('#parent-category-select');
            // 获取父分类的子分类
            var sons = categories[current_cid].sons;
            if (sons.length === 0) {
                parentCategorySelect.parent().removeClass('col-md-4');
                subCategorySelect.parent().addClass('hidden');
                // 子分类加入值为父分类 ID 的选项并选中
                subCategorySelect.append("<option value=\""+ current_cid +"\" selected></option>");
            }
            else
            {
                // 清空子分类选项
                subCategorySelect.empty();
                parentCategorySelect.parent().addClass('col-md-4');
                subCategorySelect.parent().removeClass('hidden');
                // 子分类加入选项
                subCategorySelect.append("<option value=\"\" disabled selected>{{ lang('Pick a son category') }}</option>");
                for (var i in sons)
                {
                    subCategorySelect.append("<option value=\""+ sons[i].id +"\">"+ sons[i].name +"</option>");
                }
            }
        });

        // 触发 change 事件
        @if(Route::currentRouteName() == 'topics.create')
            if ($("#parent-category-select").val() !== null)
            {
                $("#parent-category-select").trigger('change');
            }
        @endif


        var simplemde = new SimpleMDE({
            spellChecker: false,
            autosave: {
                enabled: true,
                delay: 5000,
                unique_id: "topic_content{{ isset($topic) ? $topic->id . '_' . str_slug($topic->updated_at) : '' }}"
            },
            forceSync: true,
            tabSize: 4,
            toolbar: [
                "bold", "italic", "heading", "|", "quote", "code", "table",
                "horizontal-rule", "unordered-list", "ordered-list", "|",
                "link", "image", "|",  "side-by-side", 'fullscreen', "|",
                {
                    name: "guide",
                    action: function customFunction(editor){
                        var win = window.open('https://github.com/riku/Markdown-Syntax-CN/blob/master/syntax.md', '_blank');
                        if (win) {
                            //Browser has allowed it to be opened
                            win.focus();
                        } else {
                            //Browser has blocked it
                            alert('Please allow popups for this website');
                        }
                    },
                    className: "fa fa-info-circle",
                    title: "Markdown 语法！",
                },
                {
                    name: "publish",
                    action: function customFunction(editor){
                        $('#topic-submit').click();
                    },
                    className: "fa fa-paper-plane",
                    title: "发布文章",
                }
            ],
        });

        inlineAttachment.editors.codemirror4.attach(simplemde.codemirror, {
            uploadUrl: Config.routes.upload_image,
            extraParams: {
              '_token': Config.token,
            },
            onFileUploadResponse: function(xhr) {
                var result = JSON.parse(xhr.responseText),
                filename = result[this.settings.jsonFieldName];

                if (result && filename) {
                    var newValue;
                    if (typeof this.settings.urlText === 'function') {
                        newValue = this.settings.urlText.call(this, filename, result);
                    } else {
                        newValue = this.settings.urlText.replace(this.filenameTag, filename);
                    }
                    var text = this.editor.getValue().replace(this.lastValue, newValue);
                    this.editor.setValue(text);
                    this.settings.onFileUploaded.call(this, filename);
                }
                return false;
            }
        });
    });



</script>
@stop
